const {dialog} = require('electron')
const path = require('path')
const localDB = require('./localDB')
const tools = require('./tools')
const fs = require('fs')
const {app, BrowserWindow, nativeTheme, Tray, nativeImage, Menu, ipcMain} = require('electron')
const {initDownload} = require('./download')
const NODE_ENV = process.env.NODE_ENV
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
let mainWindow = null
let configData = null

function createWindow() {
    // 创建浏览器窗口
    mainWindow = new BrowserWindow({
        width: 1920,
        height: 1080,
        resizable: true,
        icon: path.join(__dirname, '../dist/natalie.ico'),
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true,
            contextIsolation: true,
            enableRemoteModule: false, // 禁用 remote 模块
        },
    })
    nativeTheme.themeSource = 'dark'
    mainWindow.on('closed', (res) => {
        console.log('=== app closed ===')
        app.quit()
    })
    mainWindow.loadURL(
        NODE_ENV === 'development' ? 'http://localhost:10100' : `file://${path.join(__dirname, '../index.html')}`,
    )
    initDownload(mainWindow)
    if (NODE_ENV === 'development') {
        mainWindow.webContents.openDevTools()
    }

    //  监听右键菜单触发
    mainWindow.webContents.on('context-menu', (event, params) => {
        const selectEnabled = !!params.selectionText.trim().length
        const template = []
        if (params.isEditable) {
            template.unshift(
                ...[
                    {
                        label: '粘贴',
                        role: 'paste',
                    },
                ],
            )
        }
        if (selectEnabled) {
            //选中文字时
            template.unshift(
                ...[
                    {
                        label: '复制',
                        role: 'copy',
                        visible: () => !selectEnabled,
                    },
                    {
                        label: '剪切',
                        role: 'cut',
                    },
                ],
            )
        }
        if (template.length) {
            const RightMenu = Menu.buildFromTemplate(template)
            RightMenu.popup()
        }
    })
}

const defaultTemplate = [
    {
        label: '编辑',
        submenu: [
            {role: 'cut', label: '剪切'},
            {role: 'copy', label: '复制'},
            {role: 'paste', label: '粘贴'},
            {role: 'selectAll', label: '全选'},
        ],
    },
    {
        label: '窗口',
        submenu: [
            {role: 'reload', label: '刷新'},
            {role: 'forceReload', label: '强制刷新'},
            {role: 'toggleDevTools', label: '控制台'},
            {type: 'separator'},
            {role: 'resetZoom', label: '重置'},
            {role: 'zoomIn', label: '放大'},
            {role: 'zoomOut', label: '缩小'},
            {type: 'separator'},
            {role: 'togglefullscreen', label: '全屏'},
        ],
    },
    {
        role: 'help',
        label: '帮助',
        submenu: [
            {
                label: '关于应用',
                click: async () => {
                    const {shell} = require('electron')
                    await shell.openExternal('http://www.psn.asia/printer.html')
                },
            },
        ],
    },
]
// 安全刷新窗口的 IPC 监听
ipcMain.on('safe-refresh', () => {
    if (mainWindow && !mainWindow.isDestroyed()) {
        mainWindow.webContents.once('did-finish-load', () => {
            mainWindow.webContents.send('window-reloaded')
        })
        mainWindow.reload()
    }
})

// 普通刷新窗口的 IPC 监听
ipcMain.on('refresh-window', () => {
    if (mainWindow && !mainWindow.isDestroyed()) {
        mainWindow.reload()
    }
})
// 在 ipcMain 监听部分添加
ipcMain.on('get-screens', (event) => {
    event.returnValue = require('electron').screen.getAllDisplays()
})
const menu = Menu.buildFromTemplate(defaultTemplate)
Menu.setApplicationMenu(menu)

let tray
// 这段程序将会在 Electron 结束初始化和创建浏览器窗口的时候调用部分 API 在 ready 事件触发后才能使用。
app.whenReady().then(() => {
    const icon = nativeImage.createFromPath(path.join(__dirname, '../dist/appicon.png'))
    tray = new Tray(icon)

    const exePath = path.dirname(process.execPath)
    const jsonPath = path.join(exePath, 'config.json')
    console.log('========================  open file', jsonPath)
    fs.readFile(jsonPath, 'utf8', (err, data) => {
        if (err) {
            tools.showErrorAndQuit('加载配置文件失败')
        }
        try {
            // 解析读取到的 JSON 字符串
            configData = JSON.parse(data)
            // console.log('success data=', configData)
            ipcMain.handle('get-config-data', async () => {
                return configData
            })

            ipcMain.on('get-shared-data', (event) => {
                event.returnValue = configData
            })

            /*--- 配置文件读取账号密码后, 连接本地数据库 ---*/
            localDB.mysqlCon.host = configData.mysql_host
            localDB.mysqlCon.port = configData.mysql_port
            localDB.mysqlCon.user = configData.mysql_user
            localDB.mysqlCon.password = configData.mysql_password
            localDB.mysqlCon.database = configData.mysql_database
            localDB.mysqlCon.handleConnect()

            ipcMain.on('point_save_request', (event, args) => {
                // console.log("收到参数: ", args)
                localDB.mysqlCon.point_save(args).then(res => {
                    event.sender.send("point_save_response", res)
                }).catch(err => {
                    event.sender.send("point_save_response", err)
                })
            })

            ipcMain.on('point_list_request', (event, args) => {
                // console.log("收到参数: ", args)
                localDB.mysqlCon.point_list(args).then(res => {
                    event.sender.send("point_list_response", res)
                }).catch(err => {
                    event.sender.send("point_list_response", err)
                })
            })

            ipcMain.on('tendency_chart_request', (event, args) => {
                // console.log("收到参数: ", args)
                localDB.mysqlCon.tendency_chart(args).then(res => {
                    event.sender.send("tendency_chart_response", res)
                }).catch(err => {
                    event.sender.send("tendency_chart_response", err)
                })
            })

            ipcMain.on('point_list_v2_request', (event, args) => {
                // console.log("收到参数: ", args)
                localDB.mysqlCon.point_list_v2(args).then(res => {
                    event.sender.send("point_list_v2_response", res)
                }).catch(err => {
                    event.sender.send("point_list_v2_response", err)
                })
            })

            createWindow()
        } catch (err) {
            tools.showErrorAndQuit('配置文件解析失败')
        }
    })

    app.on('activate', function () {
        // 通常在 macOS 上，当点击 dock 中的应用程序图标时，如果没有其他打开的窗口，那么程序会重新创建一个窗口。
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})
// 除了 macOS 外，当所有窗口都被关闭的时候退出程序。 因此，通常对程序和它们在任务栏上的图标来说，应当保持活跃状态，直到用户使用 Cmd + Q 退出。
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})
